package com.thinkingstar.filter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.util.*;

/**
 * @Author : sy
 * @Description : 加载config.properties，将URL写入到param.js中
 * @Date : Created in 17:02 2018/4/20
 */
public class LoadConfigFileServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

    private Properties properties = null;

    public Map<String,String> properties_map;

    public static Map<String,List<Map<String, String>>> CITY_LNG_LAT_MAP = new HashMap<String,List<Map<String, String>>>();

    public void init() throws ServletException {
        // 加载config.properties，将URL写入到param.js中
        loadConfigWriteToParamJS();
    }


    private void loadConfigWriteToParamJS(){
        try {
            InputStream in = LoadConfigFileServlet.class.getClassLoader().getResourceAsStream("config.properties");
            properties = new Properties();
            properties.load(in);
            //关闭资源
            in.close();
            //保存所有的键值
            Map<String,String> properties_map=new HashMap<String,String>();
            Enumeration en = properties.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String Property = properties.getProperty(key);
                properties_map.put(key, Property);
            }
            // 写入到param.js中
            String urlParamString = "";
            for(String thisKey : properties_map.keySet()){
                if(thisKey.startsWith("map")){
                    urlParamString += "var "+thisKey+" = '"+properties_map.get(thisKey)+"'; \n";
                }
            }
            String webRoot_path = getServletContext().getRealPath("/");
            //String webRoot_path = getServletContext().getContextPath();
            File paramjs_file =new File(webRoot_path+"/static/js/common/param.js");
            if(!paramjs_file.exists()){
                paramjs_file.createNewFile();
            }
            FileWriter fileWritter = new FileWriter(paramjs_file.getPath());
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write(urlParamString);
            bufferWritter.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void destroy() {
        System.out.println("*********  loadConfigFileServlet destroy  *********");
    }

}
